local json = require "cjson"

--返回数据方法
local function responseMsg(code, msg, data)
    local rtn = {}
    rtn['code'] = code
    rtn['msg'] = msg
    rtn['data'] = data
    return json.encode(rtn)
end

local function getSubscription(roundId, skuId, userId)
    local roundSubscriptionCacheKey = string.format("zlj:jqq:activity:seckill:round:subscription:%d", roundId)
    local subscription = 0
    local field = string.format("%d_%d", skuId, userId)
    subscriptionCache = red:hget(roundSubscriptionCacheKey, field)
    if subscriptionCache == "1" then
        subscription = 1
    end
    return subscription
end

local function getInventory(roundId, skuId)
    local cacheKey = string.format("zlj:jqq:activity:seckill:round:inventory:%d:%d", roundId, skuId)
    return red:llen(cacheKey)
end

local function getRoundStatus(roundId, skuId, startTimestamp, endTimestamp)
    local currentTimestamp = os.time()
    local dataStatus = 0
    notifyTimestamp = startTimestamp - 600
    if currentTimestamp < notifyTimestamp then
        dataStatus = 1
    elseif currentTimestamp < startTimestamp then
        dataStatus = 2
    elseif currentTimestamp >= startTimestamp and currentTimestamp <= endTimestamp then
        if getInventory(roundId, skuId) > 0 then
            dataStatus = 3
        else
            dataStatus = 4
        end
    else
        dataStatus = 5
    end
    return dataStatus
end

ngx.header["Access-Control-Allow-Origin"] = "*"
ngx.header["Access-Control-Allow-Headers"] = "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range, userid, agent, brandid, language, token"

--验证参数
local arg = ngx.req.get_uri_args()
local roundId = arg.round_id
if not roundId or #roundId <= 0 then
    ngx.say(responseMsg('-1', 'round_id参数有误', nil))
    return
end

-- 数据库、redis 等基础配置项
local env = ''
local mysql_prop = {}
local redis_prop = {}
local redis_prop_home = {}
if env == 'local' then
    mysql_prop = {
        host = "zljsz-testenvironmentdb.mysql.rds.aliyuncs.com",
        port = 3306,
        database = "panda_recovery",
        user = "code_test",
        password = "reVvtDiN2g3JaCxc"
    }

    redis_prop = {
        host = "zljsz-testenvironmentdb.redis.rds.aliyuncs.com",
        port = 6379,
        auth = 'lzWu9gskZ9OQrnOP'
    }
    redis_prop_home = {
        host = "zljsz-testenvironmentdb.redis.rds.aliyuncs.com",
        port = 6379,
        auth = 'lzWu9gskZ9OQrnOP'
    }
elseif env == 'test' then
    mysql_prop = {
        host = "zljsz-testenvironmentdb.mysql.rds.aliyuncs.com",
        port = 3306,
        database = "panda_recovery",
        user = "code_test",
        password = "reVvtDiN2g3JaCxc"
    }

    redis_prop = {
        host = "zljsz-testenvironmentdbvpc.redis.rds.aliyuncs.com",
        port = 6379,
        auth = 'lzWu9gskZ9OQrnOP'
    }
    redis_prop_home = {
        host = "zljsz-testenvironmentdbvpc.redis.rds.aliyuncs.com",
        port = 6379,
        auth = 'lzWu9gskZ9OQrnOP'
    }
else
    mysql_prop = {
        host = "rm-wz9s54k9r047b5012rw.mysql.rds.aliyuncs.com",
        port = 3306,
        database = "panda_recovery",
        user = "code_recovery",
        password = "xGvyhcnXL49RWz1N"
    }

    redis_prop = {
        host = "zljsz-recoverydbvpc.redis.rds.aliyuncs.com",
        port = 6379,
        auth = 'NeSt6Wauy3ZKqEMR'
    }
    redis_prop_home = {
        host = "zljsz-redis1dbvpc.redis.rds.aliyuncs.com",
        port = 6379,
        auth = 'JtS42CKZsepk88EX'
    }
end

--连接redis
local redis = require "resty.redis"
zljRed = redis:new()
local ok, err = zljRed:connect(zljRedisConfig['host'], zljRedisConfig['port'])   --连接redis
if not ok then
    ngx.say(responseMsg('-1', json.encode(err), nil))
    return
end
--连接redis密码
ok, err = zljRed:auth(zljRedisConfig['auth'])   --连接redis
if not ok then    -- 链接失败的时候
    ngx.say(responseMsg('-1', json.encode(err), nil));
    return
end

local token = arg.token
local userId = 0;
if token and #token > 0 then
    userId = zljRed:get(token);
end
if userId == ngx.null then
    ngx.say(responseMsg('-1', "用户token已过期", nil));
    return
end

red = redis:new()
local ok, err = red:connect(recoveryRedisConfig['host'], recoveryRedisConfig['port'])   --连接redis
if not ok then
    ngx.say(responseMsg('-1', json.encode(err), nil))
    return
end
--连接redis密码
ok, err = red:auth(recoveryRedisConfig['auth'])   --连接redis
if not ok then    -- 链接失败的时候
    ngx.say(responseMsg('-1', json.encode(err), nil));
    return
end

red:select(1)

local roundCacheKey = "zlj:jqq:activity:seckill:round:entity:"..roundId
local roundData = red:get(roundCacheKey)
if roundData == ngx.null then
    ngx.say(responseMsg("-1", "round不存在", nil))
    return
end

roundData = json.decode(roundData)
if os.time() < tonumber(roundData['start_timestamp']) then
    roundData['remain_interval'] = tonumber(roundData['start_timestamp']) - os.time();
elseif os.time() < tonumber(roundData['end_timestamp']) then
    roundData['remain_interval'] = tonumber(roundData['end_timestamp']) - os.time();
else
    roundData['remain_interval'] = 0
end

if roundData["goods"] then
    for k, v in pairs(roundData["goods"]) do
        if userId ~= 0 and userId ~= ngx.null then
            roundData["goods"][k]["subscription"] = getSubscription(roundId, v["sku_id"], userId)
        end
        roundData["goods"][k]["status"] = getRoundStatus(roundData['round_id'], v["sku_id"], roundData['start_timestamp'], roundData['end_timestamp'])
    end
end

ngx.header.content_type = "application/json"
ngx.say(responseMsg("1", "", roundData))
return
